<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>回收执行汇总</title>
    <link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.3.3/themes/default/easyui.css"></link>
    <link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.3.3/themes/icon.css"></link>
    <script type="text/javascript" src="/static/jquery-easyui-1.3.3/jquery.min.js"></script>
    <script type="text/javascript" src="/static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>

    <script type="text/javascript" src="/static/js/date.js"></script>
    <script src="/static/js/FileSaver.min.js"></script>
    <script src="/static/js/xlsx.full.min.js"></script>
    <script type="text/javascript">

        var url;
        //禁止整体该页面的右键弹出html相关,不阻碍easyui右键
        $(function () {
            $(document).bind('contextmenu', function (e) {
                e.preventDefault();
                $('#tree-0').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            });
        });
        //加载部门tree类别 (领料单位)
        function openDeptListChoose() {
            $("#deptList").dialog("open").dialog("setTitle", "选择归还单位");
            $("#deptTree").tree({
                url: '/admin/bumen/loadBumenTree',
                onLoadSuccess: function (node, data) {
                    $("#deptTree").tree('expandAll');
                },
                onDblClick: function (node) {

                },
                //右键选择树形菜单操作
                onContextMenu: function (e, node) { //右键时触发事件                      
                    e.preventDefault(); //阻止浏览器捕获右键事件
                },
                //单击某类别 展示不同详细和按钮选择
                onClick: function (node) {
                    if (node.attributes.state == 2) { // 假如是二级菜单,可以删除
                        $("#deptNameList").datagrid('load', {
                            "w_id": node.id
                        });
                    } else if (node.attributes.state == 1) {
                        $("#deptNameList").datagrid('load', {
                            "o_id": node.id
                        });
                    }
                }
            });
            loadDeptDataGrid();
        }

        //加载部门数据表格
        function loadDeptDataGrid() {
            $("#deptNameList").datagrid({
                //双击事件
                onDblClickRow: function (index, row) {
                    $("#deptId").val(row.id);
                    $("#deptName").val(row.bumenmingcheng);
                    $("#deptList").dialog("close");
                },
                onRowContextMenu: function (e, rowIndex, rowData) { //右键时触发事件                      
                    e.preventDefault(); //阻止浏览器捕获右键事件
                },
            });
        }
        // 查询部门
        function searchDept() {
            $("#deptNameList").datagrid('load', {
                "bumenmingcheng": $("#deptSearch").val()
            })
        }

        //填充部门选择
        function saveDeptChoose(){
            var node = $('#storeTree').tree('getSelected');
            $("#deptId").val(node.id);
            $("#deptName").val(node.text);
            $("#deptList").dialog("close");
        }


        $(document).ready(function () {

            $("#s_btime").datebox("setValue", genLastMonthDayStr()); // 设置上个月日期
            $("#s_etime").datebox("setValue", genTodayStr()); // 设置当前日期

            $('#dg').datagrid({
                rowStyler:function(index,row){
                    if (row.huishouzhuangtai=="全部回收"){
                        return 'background-color:GreenYellow;';
                        // color:blue;font-weight:bold;
                    }else if(row.huishouzhuangtai=="未回收"){
                        return 'background-color:white;';
                    }else if(row.huishouzhuangtai=="部分回收"){
                        return 'background-color:orange;';
                    }else if(row.huishouzhuangtai=="超量回收"){
                        return 'background-color:red;';
                    }else if(row.huishouzhuangtai=="部分退库"){
                        return 'background-color:#ffcc5c';
                    }else if(row.huishouzhuangtai=="全部退库"){
                        return 'background-color:#96ceb4';
                    }
                },
                onRowContextMenu: function (e, rowIndex, rowData) { //右键时触发事件                      
                    e.preventDefault(); //阻止浏览器捕获右键事件
                    $(this).datagrid("clearSelections"); //取消所有选中项
                    $(this).datagrid("selectRow", rowIndex); //根据索引选中该行
                    $('#grid-data').menu('show', {
                        left: e.pageX,//在鼠标点击处显示菜单
                        top: e.pageY
                    });
                    e.preventDefault();  //阻止浏览器自带的右键菜单弹出
                },
                // onClickRow: function (index, row) {
                //     $("#dg2").datagrid({
                //         url: '/admin/returnList/listGoods',
                //         queryParams: {
                //             returnListId: row.id
                //         }
                //     });
                // }
            });

        });


        function search() {
            $('#dg').datagrid('loadData', {total: 0, rows: []});
            var s_begin = $("#s_begin").datebox("getValue");
            var s_end = $("#s_end").datebox("getValue");
            var typeId = $("#typeId").val();
            var codeOrName = $("#codeOrName").val();
            $.post("/admin/purchaseList/listCount", {
                bPurchaseDate: s_begin,
                ePurchaseDate: s_end,
                "type.id": typeId,
                codeOrName: codeOrName
            }, function (result) {
                var rows = result.rows;
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    var goodsRows = row.purchaseListGoodsList;
                    for (var j = 0; j < goodsRows.length; j++) {
                        var goodsRow = goodsRows[j];
                        $('#dg').datagrid('appendRow', {
                            number: row.purchaseNumber,
                            type: "进货",
                            date: row.purchaseDate,
                            supplierName: row.supplier.name,
                            code: goodsRow.code,
                            name: goodsRow.name,
                            model: goodsRow.model,
                            typeName: goodsRow.type.name,
                            unit: goodsRow.unit,
                            price: goodsRow.price,
                            num: goodsRow.num,
                            amount: goodsRow.price * goodsRow.num
                        });
                    }
                }
            }, "json");


            $.post("/admin/returnList/listCount", {
                bReturnDate: s_begin,
                eReturnDate: s_end,
                "type.id": typeId,
                codeOrName: codeOrName
            }, function (result) {
                var rows = result.rows;
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    var goodsRows = row.returnListGoodsList;
                    for (var j = 0; j < goodsRows.length; j++) {
                        var goodsRow = goodsRows[j];
                        $('#dg').datagrid('appendRow', {
                            number: row.returnNumber,
                            type: "退货",
                            date: row.returnDate,
                            supplierName: row.supplier.name,
                            code: goodsRow.code,
                            name: goodsRow.name,
                            model: goodsRow.model,
                            typeName: goodsRow.type.name,
                            unit: goodsRow.unit,
                            price: goodsRow.price,
                            num: goodsRow.num,
                            amount: goodsRow.price * goodsRow.num
                        });
                    }
                }
            }, "json");
        }

        function chooseGoodsType() {
            $("#dlg2").dialog("open").dialog("setTitle", "选择商品类别");
            $("#typeTree").tree({
                url: '/admin/goodsType/loadTreeInfo',
                onLoadSuccess: function (node, data) {
                    var rootNode = $("#typeTree").tree('getRoot');
                    $("#typeTree").tree('expand', rootNode.target);
                }
            });
        }

        function saveGoodsTypeChoose() {
            var node = $('#typeTree').tree('getSelected'); // 获取选中节点
            $("#typeId").val(node.id);
            $("#typeName").val(node.text);
            $("#dlg2").dialog("close");
        }

        function closeGoodsTypeChooseDialog() {
            $("#dlg2").dialog("close");
        }

        function searchZhixinghuizong() {
            $("#dg").datagrid('load', {
                duiyingchukudanhao: $("#huishoudanhaoinput").val(),
                liangliaodanwei:$("#deptName").val(),
                s_btime:$("#s_btime").datebox("getValue"),
                s_etime:$("#s_etime").datebox("getValue"),
                mingchengguige:$("#mingchengguigeinput").val(),
                huishouzhuangtai:$("#huishouzhuangtaiselect").combobox('getValue'),
                liangliaoren:$("#liangliaoren").val()
                // "codeOrName":$("#codeOrName").val()
            });
        }

    </script>
</head>
<body style="margin: 1px">

<table id="dg" title="回收执行汇总" class="easyui-datagrid" fit="true"
       url="/admin/huishouzhixing/getSelective" pageList=[10,20,30,40,50,1000000]
       fitColumns="true" pagination="true" rownumbers="true"
       toolbar="#tb">
    <thead>
    <tr>
        <th field="id" width="20" align="center" sortable="true">id</th>
        <th field="duiyingchukudanhao" width="75" align="center" sortable="true">对应出库单号</th>
        <th field="huishouzhuangtai" width="45" align="center" sortable="true">回收状态</th>
        <th field="mingchengguige" width="75" align="center" sortable="true">名称规格</th>
        <th field="danwei" width="30" align="center" sortable="true">单位</th>
        <th field="chukushuliang" width="30" align="center" sortable="true">出库数量</th>
        <th field="tuikushuliang" width="30" align="center" sortable="true">退库数量</th>
        <th field="huishoushuliang" width="30" align="center" sortable="true">回收数量</th>
        <th field="weihuishoushuliang" width="30" align="center" sortable="true">未回收数量</th>
        <th field="liangliaodanwei" width="30" align="center" sortable="true">领料单位</th>
        <th field="liangliaoren" width="30" align="center" sortable="true">领料人</th>
        <th field="createtime" width="60" align="center" sortable="true">创建时间</th>
    </tr>
    </thead>
</table>

<div id="tb">
    <div style="padding-bottom: 5px">
        <fieldset style="border-color: #E7F0FF">
            <legend>统计设置</legend>
            <tr>
                <td>&nbsp;回收单号：&nbsp;<input type="text" id="huishoudanhaoinput" name="wuliaoshengoudanhao" size="20"
                                            onkeydown="if(event.keyCode==13) searchZhixinghuizong()"/>
                    &nbsp;&nbsp;
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;领料单位：<input type="text" id="deptName" name="liangliaodanwei"
                                                        style="width: 90px;" readonly="readonly"
                                                        onclick="openDeptListChoose()" required="true"/>
                    <input type="hidden" id="projId"/>
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;起始日期：&nbsp;
                    <input id="s_btime" class="easyui-datebox" editable=false style="width:100px">
                    &nbsp;&nbsp;-&nbsp;&nbsp;
                    <input id="s_etime" class="easyui-datebox" editable=false style="width:100px">
                </td>
                <td></td>
            </tr>
            <br>
            <tr>
                <td>
                    &nbsp;物料名称：&nbsp;<input type="text" id="mingchengguigeinput" name="mingchengguige" size="20"
                                            onkeydown="if(event.keyCode==13) searchZhixinghuizong()"/>
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;回收状态：<select class="easyui-combobox" id="huishouzhuangtaiselect"
                                                         name="huishouzhuangtai"
                                                         style="width: 160px;" editable="false" panelHeight="auto">
                    <option value="">未选择</option>
                    <option value="全部回收">全部回收</option>
                    <option value="未回收">未回收</option>
                    <option value="部分回收">部分回收</option>
                    <option value="超量回收">超量回收</option>
                </select>
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;领料人：&nbsp;<input type="text" id="liangliaoren" name="liangliaoren" size="20"
                                           onkeydown="if(event.keyCode==13) searchZhixinghuizong()"/>
                    &nbsp;&nbsp;<a href="javascript:searchZhixinghuizong()" class="easyui-linkbutton" iconCls="icon-search"
                                   plain="true">搜索</a>
                    &nbsp;&nbsp;-&nbsp;&nbsp;
                    <a href="javascript:void(0)" id="export_excel" iconCls="icon-save" class="easyui-linkbutton"
                       plain="true">保存数据</a>
                </td>
            </tr>
        </fieldset>
    </div>
</div>

<div id="dlg2" class="easyui-dialog" style="width:180px;height:300px;padding: 10px 10px;top: 52px;left: 80px"
     closed="true" buttons="#dlg-buttons2">

    <ul id="typeTree" class="easyui-tree"></ul>

</div>

<div id="dlg-buttons2">
    <a href="javascript:saveGoodsTypeChoose()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">选择</a>
    <a href="javascript:closeGoodsTypeChooseDialog()" class="easyui-linkbutton" iconCls="icon-cancel"
       plain="true">关闭</a>
</div>

<!--查询部门列表-->
<div id="deptList" class="easyui-dialog" style="width:800px;height:460px;"
     closed="true" data-options="onClose:function(){$('#s_codeOrDeptName').val('');}">
    <div class="easyui-layout" style="width:100%;height:100%;">

        <div region="north" style="height: 50px;">
            <div style="padding-top: 8px;padding-left: 40px;">
                &nbsp;部门名称：&nbsp;<input type="text" id="deptSearch" size="30"
                                              onkeydown="if(event.keyCode==13) searchDept()"/>
                <a href="javascript:searchDept()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
            </div>
        </div>
        <div region="west" style="width: 200px" title="领料单位分类" split="true" data-options="collapsible:false">
            <div style="overflow-x: auto; overflow-y: auto; height: 90%; width:98%;">
                <ul id="deptTree" class="easyui-tree" style="padding: 10px"></ul>
            </div>
            <div style="position:absolute;bottom: 10px;left: 15px">
                <a href="javascript:saveDeptChoose(1)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'">选择</a>
                <!--<a id="del" href="javascript:deleteGoodsType()" class="easyui-linkbutton" data-options="iconCls:'icon-remove',disabled:true">删除</a>-->
            </div>
        </div>
        <div region="center">
            <table id="deptNameList" title="领料单位列表" class="easyui-datagrid"
                   fitColumns="true" pagination="true" rownumbers="true" singleSelect="true"
                   url="/admin/dbumen/getSelective" fit="true" toolbar="#tb-bm">
                <thead>
                <tr>
                    <th field="id" width="30" hidden=true align="center">编号</th>
                    <th field="bumenmingcheng" width="150" align="center">单位名称</th>
                    <th field="createtime" width="90" align="left">创建时间</th>
                </tr>
                </thead>
            </table>
            <div id="tb-bm">
                <div>
                    <a href="javascript:saveDeptChoose(2)" class="easyui-linkbutton" iconCls="icon-ok"
                       plain="true">选择</a>
                </div>
            </div>
        </div>
    </div>
</div>

<!--大屏幕上右键datagrid dlg-->
<div id="grid-data" class="easyui-menu" style="width: 80px; display: none;">
    <!--<div id="grid-data-edit" href="javascript:openDetailsModifyDialog()" data-options="iconCls:'icon-edit'">修改</div>-->
    <!--<div id="grid-data-delete" href="javascript:deleteDetails()" data-options="iconCls:'icon-remove'" plain="true">删除-->
    <!--</div>-->
</div>
<!--二级菜单右键弹出-->
<div id="tree-2" class="easyui-menu" style="width: 80px; display: none;">
    <!--<div id="tree-2-delete" href="javascript:deleteType()" data-options="iconCls:'icon-remove'">删除二级菜单</div>-->
</div>
<!--一级菜单右键弹出-->
<div id="tree-1" class="easyui-menu" style="width: 80px; display: none;">
    <!--<div id="tree-1-add-2" href="javascript:openTypeAddDialog()" data-options="iconCls:'icon-add'">添加二级菜单</div>-->
    <!--<div id="tree-1-delete" href="javascript:deleteType()" data-options="iconCls:'icon-remove'">删除一级菜单</div>-->
</div>
<!--树形菜单右键弹出-->
<div id="tree-0" class="easyui-menu" style="width: 80px; display: none;">
    <!--<div id="tree-0-add-1" href="javascript:openTypeAddDialog(0)" data-options="iconCls:'icon-add'">添加一级菜单</div>-->
    <!--<div id="tree-0-refresh" href="javascript:reloadTree()" data-options="iconCls:'icon-reload'">重新加载类别</div>-->
</div>

</body>
<script>
    // 导出excel按钮
    $("#export_excel").click(exportExcel);

    // 导出excel
    function exportExcel() {
        //获得选中记录 多选
        var row = $('#dg').datagrid('getRows');
        // var row = $('#dg').datagrid('getSelections');
        // 去除不需要导出的实体字段
        var deleteKey = ['tuikushuliang','weihuishoushuliang','what',
            'chukushijian','updatetime','s_btime','s_etime','sort','order'
        ];
        for (var i in row) {
            for (var j in deleteKey) {
                delete row[i][deleteKey[j]];
            }
        }
        if (row) {
            $.messager.confirm('确认按钮', '你确定要导出本页回收汇总数据?', function (r) {
                if (r) {
                    downloadExl(row);
                }
            })
        }
    }

    function downloadExl(data, type) {
        var keys = Object.keys(data[0]);
        var firstRow = {};
        keys.forEach(function (item) {
            console.log("item:" + item);
            firstRow[item] = item;
        });
        data.unshift(firstRow);

        var content = {};

        //把json格式的数据转换为excel的行列形式
        var sheetsData = data.map(function (item, rowIndex) {
            return keys.map(function (key, columnIndex) {
                return Object.assign({}, {
                    value: item[key],
                    position: (columnIndex > 25 ? getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1),
                });
            });
        }).reduce(function (prev, next) {
            return prev.concat(next);
        });

        sheetsData.forEach(function (item, index) {
            // content[item.position] = {v: item.value};
            if (item.value == 'id') {
                content[item.position] = {v: '序列号'};
            } else if (item.value == 'duiyingchukudanhao') {
                content[item.position] = {v: '对应出库单号'};
            } else if (item.value == 'huishouzhuangtai') {
                content[item.position] = {v: '回收状态'};
            } else if (item.value == 'mingchengguige') {
                content[item.position] = {v: '名称规格'};
            } else if (item.value == 'danwei') {
                content[item.position] = {v: '单位'};
            } else if (item.value == 'chukushuliang') {
                content[item.position] = {v: '出库数量'};
            } else if (item.value == 'huishoushuliang') {
                content[item.position] = {v: '回收数量'};
            } else if (item.value == 'liangliaodanwei') {
                content[item.position] = {v: '领料单位'};
            } else if (item.value == 'liangliaoren') {
                content[item.position] = {v: '领料人'};
            } else if (item.value == 'createtime') {
                content[item.position] = {v: '创建时间'};
            } else {
                if (item.value == null || item.value == undefined || item.value == 'null') {
                    content[item.position] = {v: ''};  //remember
                } else {
                    content[item.position] = {v: item.value};  //remember
                }
            }
        });

        //设置区域,比如表格从A1到D10,SheetNames:标题
        var coordinate = Object.keys(content);
        var workBook = {
            SheetNames: ["1"],
            Sheets: {
                "1": Object.assign({}, content, {"!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1]}),
            }
        };

        //这里的数据是用来定义导出的格式类型
        var excelData = XLSX.write(workBook, {bookType: "xlsx", bookSST: false, type: "binary"});
        var blob = new Blob([string2ArrayBuffer(excelData)], {type: ""});

        // filename = "石油焦";
        $.messager.prompt("输入框", "请输入保存文件名.", function (filename) {
            if (filename) {
                var nowTime = new Date().toLocaleDateString();
                saveAs(blob, filename + "-回收汇总" + nowTime + ".xlsx"); //文件名
            }
        });
    }

    //字符串转字符流
    function string2ArrayBuffer(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) {
            view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
    }

    //将指定的自然数转换为26进制表示. 映射关系: [0-25] -> [A-Z]
    function getCharCol(n) {
        var temCol = "",
            s = "",
            m = 0;
        while (n > 0) {
            m = n % 26 + 1;
            s = String.fromCharCode(m + 64) + s;
            n = (n - m) / 26;
        }
        return s;
    }

</script>
</html>